package cn.momoky.ccool.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebUtils {

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        return requestAttributes.getRequest();
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        return requestAttributes.getResponse();
    }

    public static String getHost() {
        HttpServletRequest req = getRequest();
        String ips = req.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ips) || ips.equalsIgnoreCase("unknown")) {
            ips = req.getHeader("Proxy-Client-Ip");
        }
        if (StringUtils.isEmpty(ips) || ips.equalsIgnoreCase("unknown")) {
            ips = req.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ips) || ips.equalsIgnoreCase("unknown")) {
            ips = req.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(ips) || ips.equalsIgnoreCase("unknown")) {
            ips = req.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(ips) || ips.equalsIgnoreCase("unknown")) {
            ips = req.getRemoteAddr();
        }

        if (StringUtils.isEmpty(ips)) return req.getRemoteHost();
        String[] ipList = ips.split(",");

        return ipList[0].trim();
    }

    public static int getPort() {
        HttpServletRequest req = getRequest();
        return req.getRemotePort();
    }

    public static String getUserAgent() {
        HttpServletRequest req = getRequest();
        return req.getHeader("User-Agent");
    }
}
